package com.shuiyun.jtt.server;

import com.shuiyun.jtt.handler.FrameDecoder;
import com.shuiyun.jtt.handler.JTMessageHandler;
import com.shuiyun.jtt.handler.MessageCodecHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NettyRuntime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author shuiyun
 * @description 网关服务
 * @date 2022-04-16 16:57
 */
@Slf4j
@Service
public class GatewayServer {

    private final static LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    private final static byte[] DELIMITER = new byte[]{0x7e};
    private final MessageCodecHandler messageCodecHandler;
    private final JTMessageHandler jtMessageHandler;

    public GatewayServer(MessageCodecHandler messageCodecHandler, JTMessageHandler jtMessageHandler) {
        this.messageCodecHandler = messageCodecHandler;
        this.jtMessageHandler = jtMessageHandler;
    }

    /**
     * 网关服务 随项目自动启动
     * @author shuiyun
     * @date 2022/4/16
     */
    @PostConstruct
    public void start() throws Exception {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup(NettyRuntime.availableProcessors());
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.group(boss, worker);
        serverBootstrap.option(NioChannelOption.SO_BACKLOG, 1024)
                .option(NioChannelOption.SO_REUSEADDR, true)
                .childOption(NioChannelOption.TCP_NODELAY, true)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline().addLast(new FrameDecoder())
                                .addLast(messageCodecHandler)
                                .addLast(jtMessageHandler);
                    }
                });

        ChannelFuture channelFuture = serverBootstrap.bind(8023).sync();
        log.info("启动netty port:{}",8023);
        Channel channel = channelFuture.channel();
        channel.closeFuture().addListener((ChannelFutureListener) future -> {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        });

    }
}
